/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.losalpes.marketplace.pirfq.entities.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.hibernate.exception.ConstraintViolationException;

/**
 *
 * @author leon
 */
public class Persistence {

    public void persist(Object object) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFQ_jpaPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (ConstraintViolationException cve) {
            em.getTransaction().rollback();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public <T extends Object> T merge(T t) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFQ_jpaPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        T aux = null;
        try {
            aux = em.merge(t);
            em.getTransaction().commit();
        } catch (ConstraintViolationException cve) {
            em.getTransaction().rollback();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
        return aux;
    }

    public Query createNamedQuery(String nq) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFQ_jpaPU");
        EntityManager em = emf.createEntityManager();
        return em.createNamedQuery(nq);
    }

    public Query createNativeQuery(String nq) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFQ_jpaPU");
        EntityManager em = emf.createEntityManager();
        return em.createNativeQuery(nq);
    }

    public <T extends Object> T find(Class<T> type, Object o) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFQ_jpaPU");
        EntityManager em = emf.createEntityManager();
        return em.find(type, o);
    }
}
